@echo off
chcp 65001 >nul
echo ========================================
echo 强制关闭8000-8010端口程序
echo ========================================

set killed_count=0

:: 查找并关闭占用8000-8010端口的进程
for /l %%p in (8000,1,8010) do (
    echo 正在检查端口 %%p...

    :: 使用netstat查找占用端口的进程
    for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":%%p "') do (
        set pid=%%a
        if not "!pid!"=="" (
            echo 发现进程 !pid! 占用端口 %%p，正在终止...
            taskkill /F /PID !pid! >nul 2>&1
            if !errorlevel! equ 0 (
                echo ✓ 已终止进程 !pid!
                set /a killed_count+=1
            ) else (
                echo ✗ 终止进程 !pid! 失败
            )
        )
    )
)

:: 额外清理Python相关进程
echo 正在清理Python相关进程...
for /f "tokens=2" %%a in ('tasklist /FI "IMAGENAME eq python.exe" /FO CSV /NH ^| findstr "python"') do (
    set pid=%%a
    set pid=!pid:"=!
    echo 正在检查Python进程 !pid!...

    :: 检查是否是相关进程
    wmic process where "processid=!pid!" get commandline /value | findstr "800\|uvicorn\|fastapi" >nul
    if !errorlevel! equ 0 (
        echo 终止相关Python进程 !pid!...
        taskkill /F /PID !pid! >nul 2>&1
        if !errorlevel! equ 0 (
            echo ✓ 已终止Python进程 !pid!
            set /a killed_count+=1
        )
    )
)

:: 清理node进程（如果有的话）
echo 正在清理Node.js相关进程...
for /f "tokens=2" %%a in ('tasklist /FI "IMAGENAME eq node.exe" /FO CSV /NH ^| findstr "node"') do (
    set pid=%%a
    set pid=!pid:"=!
    echo 正在检查Node.js进程 !pid!...

    wmic process where "processid=!pid!" get commandline /value | findstr "800" >nul
    if !errorlevel! equ 0 (
        echo 终止相关Node.js进程 !pid!...
        taskkill /F /PID !pid! >nul 2>&1
        if !errorlevel! equ 0 (
            echo ✓ 已终止Node.js进程 !pid!
            set /a killed_count+=1
        )
    )
)

echo.
echo ========================================
echo 清理完成！共终止 %killed_count% 个进程
echo ========================================

:: 验证清理结果
echo.
echo 验证清理结果...
timeout /t 2 /nobreak >nul

set still_occupied=0
for /l %%p in (8000,1,8010) do (
    netstat -ano | findstr ":%%p " | findstr "LISTENING" >nul
    if !errorlevel! equ 0 (
        echo 端口 %%p 仍被占用
        set still_occupied=1
    )
)

if !still_occupied! equ 0 (
    echo ✓ 所有端口已完全释放！
) else (
    echo ⚠️  仍有端口被占用，请手动检查
)

pause